import { getUserInfo } from "@/models/login";
import { useHistory } from "react-router-dom";
import { createContext, useEffect, useState, useMemo } from 'react';
import { getUserPermits } from "../services/login";

export const UserContext = createContext({ userInfo: null });

export default function UserProvider({ children, dispatch }){
  const [userInfo, setUserInfo] = useState(null);
  const [userPermits, setUserPermits] = useState([])
  const history = useHistory();
  useEffect(() => {
    const userInfo = getUserInfo();

    // if(!(userInfo.type==1 || userInfo.type==4)){
    //   history.push('/404')
    // }

    if (userInfo) {
      dispatch({ type: 'user/saveCurrentUser', payload: userInfo });
      setUserInfo(userInfo);
      getUserPermits({type: userInfo.type}).then(({code, data = [], msg})=> {
        if (String(code) === '200') {
          const prunePermits = (data ?? []).filter(({is_active}) => String(is_active) === '1').map(({functionname}) => functionname)
          setUserPermits(prunePermits)
        }else{
          setUserPermits([])
        }
      }).catch(()=>{
        setUserPermits([])
      })
    } else {
      history.replace('/user/login')
    }
  }, [dispatch, history]);
  const memoValue = useMemo(() => ({
    userInfo,
    userPermits
  }), [userInfo, userPermits])
  return <UserContext.Provider value={memoValue}>
    {children}
  </UserContext.Provider>
}
